<template>
  <UserLayout :active-index="'2'" :active-menu="'tenant-center'">
    <div class="appointment-content">
      <div class="appointment-header">
        <el-button type="primary" @click="goBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回租客中心
        </el-button>
        <h2>预约申请管理</h2>
        <p>查看您提交的看房预约申请</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <!-- 预约申请列表 -->
      <div v-else class="appointment-list">
        <!-- 空状态 -->
        <el-empty v-if="appointments.length === 0" description="暂无预约申请">
          <el-button type="primary" @click="goToHouseSearch">去看房</el-button>
        </el-empty>

        <!-- 预约列表 -->
        <el-table v-else :data="appointments" style="width: 100%" stripe>
          <el-table-column prop="appointmentId" label="预约编号" width="120"></el-table-column>
          <el-table-column label="房源信息" width="200">
            <template #default="scope">
              <div class="house-info">
                <div class="house-id">房源ID: {{ scope.row.houseId }}</div>
                <div class="house-title" v-if="scope.row.houseTitle">{{ scope.row.houseTitle }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="联系方式" width="120">
            <template #default="scope">
              <div v-if="scope.row.landlordId && scope.row.agentId">
                <div>房东+中介</div>
              </div>
              <div v-else-if="scope.row.landlordId">
                <div>房东</div>
              </div>
              <div v-else-if="scope.row.agentId">
                <div>中介</div>
              </div>
              <div v-else>
                <div>待分配</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="appointmentTime" label="预约时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.appointmentTime) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row)">
                {{ getStatusText(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="联系电话" width="130">
            <template #default="scope">
              {{ scope.row.tenantPhone || '未填写' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button size="small" @click="viewDetails(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 预约详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="预约详情" width="600px">
      <div v-if="selectedAppointment" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约编号">{{ selectedAppointment.appointmentId }}</el-descriptions-item>
          <el-descriptions-item label="房源ID">{{ selectedAppointment.houseId }}</el-descriptions-item>
          <el-descriptions-item label="租客ID">{{ selectedAppointment.tenantId }}</el-descriptions-item>
          <el-descriptions-item label="房东ID">{{ selectedAppointment.landlordId || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="中介ID">{{ selectedAppointment.agentId || '无中介' }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ formatDateTime(selectedAppointment.appointmentTime) }}</el-descriptions-item>
          <el-descriptions-item label="预约状态" :span="2">
            <el-tag :type="getStatusType(selectedAppointment)">
              {{ getStatusText(selectedAppointment) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedAppointment.tenantPhone || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="拒绝原因" v-if="selectedAppointment.isRefused">{{ selectedAppointment.refusedReason || '无' }}</el-descriptions-item>
          <el-descriptions-item label="备注信息" :span="2">{{ selectedAppointment.remarkMessage || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import { ArrowLeft } from '@element-plus/icons-vue'
import api from '@/utils/api'

const router = useRouter()

// 数据
const loading = ref(false)
const dialogVisible = ref(false)
const selectedAppointment = ref(null)
const appointments = ref([])

// 返回租客中心
const goBack = () => {
  router.push('/rental/tenant')
}

// 跳转到房源搜索
const goToHouseSearch = () => {
  router.push('/house/search')
}

// 获取当前用户ID
const getCurrentUserId = () => {
  const user = localStorage.getItem('user')
  if (user) {
    try {
      const userData = JSON.parse(user)
      return userData.id || userData.userId
    } catch (error) {
      console.error('解析用户数据失败:', error)
    }
  }
  return null
}

// 获取预约列表
const fetchAppointments = async () => {
  const userId = getCurrentUserId()
  if (!userId) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }

  loading.value = true
  try {
    const response = await api.get(`/appointment/list/${userId}`)
    console.log('预约列表响应:', response)

    if (response && (response.code === 200 || response.code === '200')) {
      appointments.value = response.data || []
      console.log('获取到的预约列表:', appointments.value)
    } else {
      ElMessage.error(response?.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 查看详情
const viewDetails = (appointment) => {
  selectedAppointment.value = appointment
  dialogVisible.value = true
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未设置'
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return dateTimeStr
  }
}

// 获取状态类型
const getStatusType = (appointment) => {
  // 根据后端数据结构判断状态
  if (appointment.isRefused === true) {
    return 'danger' // 已拒绝
  } else if (appointment.isRefused === false) {
    return 'success' // 已确认
  } else if (appointment.isRefused === null) {
    return 'warning' // 待确认
  }
  return 'info'
}

// 获取状态文本
const getStatusText = (appointment) => {
  // 根据后端数据结构判断状态
  if (appointment.isRefused === true) {
    return '已拒绝'
  } else if (appointment.isRefused === false) {
    return '已确认'
  } else if (appointment.isRefused === null) {
    return '待确认'
  }
  return '未知状态'
}

// 页面加载时获取数据
onMounted(() => {
  fetchAppointments()
})
</script>

<style scoped>
.appointment-content {
  padding: 20px;
}

.appointment-header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
}

.appointment-header h2 {
  color: #2c3e50;
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.appointment-header p {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
}

.back-btn {
  position: absolute;
  top: 0;
  left: 0;
}

.loading-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.appointment-list {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.house-info {
  line-height: 1.4;
}

.house-id {
  font-size: 12px;
  color: #909399;
}

.house-title {
  font-size: 14px;
  color: #303133;
  margin-top: 2px;
}

.detail-content {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .appointment-content {
    padding: 15px;
  }

  .appointment-header h2 {
    font-size: 24px;
  }

  .back-btn {
    position: static;
    margin-bottom: 20px;
  }
}
</style>
